const express = require("express");
const router = express.Router();
const { Course, Category, Chapter, User } = require("../../models");
const { failure, success } = require("../../utils/responses");
const { paging } = require("../../utils/utils");
const { NotFoundError } = require("../../utils/errors");
/**
 * 查询课程列表
 * GET /courses
 */
router.get("/", async function (req, res, next) {
  try {
    const { query, currentPage, pageSize, offset } = paging(req);
    // 排序+分页
    const condition = {
      attributes: { exclude: ["CategoryId", "UserId", "content"] },
      where: { categoryId: query.categoryId },
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
    };
    if (!query.categoryId) {
      throw new Error("获取课程列表失败,分类ID不能为空");
    }
    // 分页查询
    const { count, rows } = await Course.findAndCountAll(condition);
    // 返回
    success(res, "查询课程列表成功", {
      courses: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询课程详情
 * GET /courses/:id
 */
router.get("/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const condition = {
      attributes: { exclude: ["CategoryId", "UserId"] },
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: Chapter,
          as: "chapters",
          attributes: ["id", "title", "rank", "createdAt"],
          order: [
            ["rank", "ASC"],
            ["id", "DESC"],
          ],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "username", "avatar", "company"],
        },
      ],
    };
    const course = await Course.findByPk(id, condition);
    if (!course) {
      throw new NotFoundError(`ID: ${id} not found`);
    }
    success(res, "查询课程详情成功", { course });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
